<template>
  <!-- 布局 -->
  <a-layout>
    <!-- 内容 -->
    <a-layout-content
      :style="{
        background: '#fff',
        padding: '24px',
        margin: 0,
        minHeight: '280px',
      }"
    >
      <p>
        <!-- 提供表单 -->
        <a-form layout="inline" :model="param">
          <a-form-item>
            <a-input v-model:value="param.name" placeholder="名称"> </a-input>
          </a-form-item>
          <a-form-item>
            <a-button
              type="primary"
              @click="handleQuery({ page: 1, size: pagination.pageSize })"
            >
              查询
            </a-button>
          </a-form-item>
          <a-form-item>
            <a-button type="primary" @click="add()"> 新增 </a-button>
          </a-form-item>
        </a-form>
      </p>
      <!-- 表格 columns列字段 data-source遍历的数据源 pagination分页 change更改触发的函数  -->
      <a-table
        :columns="columns"
        :row-key="(record) => record.id"
        :data-source="ebooks"
        :pagination="pagination"
        :loading="loading"
        @change="handleTableChange"
      >
        <!-- 电子书的封面图片 -->
        <template #cover="{ text: cover }">
          <img
            v-if="cover"
            :src="cover"
            alt="avatar"
            style="width: 20%; height: 20%"
          />
        </template>
        <!-- 分类信息绑定 -->
        <template v-slot:category="{ text: record }">
          <span
            >{{ getCategoryName(record.category1Id) }}/{{
              getCategoryName(record.category2Id)
            }}</span
          >
        </template>
        <!-- 操作按钮 -->
        <template v-slot:action="{ text, record }">
          <!--  -->
          <a-space size="small">
            <!-- 查询文档 -->
            <router-link :to="'/admin/doc?ebookId='+record.id">
              <a-button type="primary"> 文档管理 </a-button>
            </router-link>
            <!-- 编辑 -->
            <a-button type="primary" @click="edit(record)"> 编辑 </a-button>
            <!-- 二次确认组件 -->
            <a-popconfirm
              title="删除后不可恢复，是否删除"
              ok-text="是"
              cancel-text="否"
              @confirm="handleDelete(record.id)"
            >
              <a-button type="primary" danger> 删除 </a-button>
            </a-popconfirm>
          </a-space>
        </template>
      </a-table>
    </a-layout-content>
  </a-layout>

  <!-- 定义一个对话框+表单 -->
  <a-modal
    title="电子书表单"
    v-model:visible="modalVisible"
    @ok="handleModalOk"
  >
    <a-form :model="ebook" :label-col="{ span: 6 }" :wrapper-col="{ span: 18 }">
      <!-- 文件上传的组件 -->
      <a-form-item label="封面">
        <div class="clearfix">
          <a-upload
            v-model:file-list="fileList"
            list-type="picture-card"
            :customRequest="customRequest"
          >
            <div v-if="fileList.length < imgNum">
              <plus-outlined />
              <div style="margin-top: 8px">Upload</div>
            </div>
          </a-upload>
          <a-modal
            :visible="previewVisible"
            :title="previewTitle"
            :footer="null"
            @cancel="handleCancel"
          >
            <img alt="example" style="width: 100%" :src="previewImage" />
          </a-modal>
        </div>
      </a-form-item>
      <a-form-item label="名称">
        <a-input v-model:value="ebook.name" />
      </a-form-item>
      <a-form-item label="分类">
        <a-cascader
          v-model:value="categoryIds"
          :field-names="{ label: 'name', value: 'id', children: 'children' }"
          :options="level1"
        />
      </a-form-item>
      <a-form-item label="描述">
        <a-input v-model:value="ebook.description" type="textarea" />
      </a-form-item>
    </a-form>
  </a-modal>
</template>
  <script lang="ts">
import { defineComponent, onMounted, ref } from "vue";
import axios from "axios";
import { message } from "ant-design-vue";
import { Tool } from "@/utils/tool";

export default defineComponent({
  name: "AdminEbook",
  // components: {
  // },
  setup() {
    //定义ebooks对象、分页对象
    const ebooks = ref();
    const ebook = ref();
    //查询参数
    const param = ref();
    param.value = {};
    //分页参数
    const pagination = ref({
      current: 1,
      pageSize: 5,
      total: 0,
    });
    const loading = ref(false);
    const modalVisible = ref(false);
    const modalLoading = ref(false);
    //字段列表  【标题字段】 【dataIndex-关联的变量名】
    const columns = [
      {
        title: "封面",
        dataIndex: "cover",
        slots: { customRender: "cover" },
      },
      {
        title: "名称",
        dataIndex: "name",
      },
      {
        title: "分类",
        // dataIndex: "category2Id",
        slots: { customRender: "category" },
      },
      {
        title: "文档数",
        dataIndex: "docCount",
      },
      {
        title: "阅读数",
        dataIndex: "viewCount",
      },
      {
        title: "点赞数",
        dataIndex: "voteCount",
      },
      {
        title: "Action",
        key: "action",
        slots: { customRender: "action" },
      },
    ];
    //定义级联操作的数组categoryIds
    const categoryIds = ref();

    //新增-修改处理【文件名】
    let fileName = "";
    //图片上传
    // 上传图片
    const imgNum = ref(1);
    const previewVisible = ref(false);
    const previewImage = ref("");
    const previewTitle = ref("");
    const fileList = ref([]);

    //定义一个函数来根据分类id获取name
    const getCategoryName = (cid: number) => {
      let result = "";
      categorys.forEach((item: any) => {
        if (item.id === cid) {
          result = item.name;
        }
      });
      return result;
    };

    //自定义文件上传处理的函数
    const customRequest = (file: any) => {
      // 表单【FormData存放图片file的数据】
      const form = new FormData();
      form.append("file", file.file); // 表单添加文件名
      //发起请求上传图片文件
      axios
        .post("/ebook/uploadImage", form, {
          headers: { "Content-Type": "multipart/form-data" },
        })
        .then((res) => {
          if (res.data.success) {
            // 调用组件的方法，设置为成功
            file.onSuccess(res, file.file);
            file.status = "done";
            fileName = res.data.content;
          } else {
            file.onError();
            file.status = "error";
          }
        });
    };

    //取消的处理
    const handleCancel = () => {
      previewVisible.value = false;
      previewTitle.value = "";
    };

    /*
     * 分类数据查询   let categorys用于存放所有分类信息
     * */
    const level1 = ref();
    let categorys: any;
    const handleQueryCategory = () => {
      loading.value = true;
      axios.get("/category/getCategoryList").then((resp) => {
        loading.value = false;
        const data = resp.data;
        categorys = data.content;
        //判断
        if (data.success) {
          console.log("原始数据：", data.content);
          level1.value = [];
          level1.value = Tool.array2Tree(data.content, 0);
          console.log("树形结构：", level1);
          //再查询book信息
          //发起ebook信息的查询
          handleQuery({
            page: pagination.value.current,
            size: pagination.value.pageSize,
          });
        } else {
          message.error(data.message);
        }
      });
    };

    //点击对话框的ok按钮触发的函数
    const handleModalOk = () => {
      //文件名的赋值
      ebook.value.cover = "/image/" + fileName;
      //把两个分类的id进行赋值
      ebook.value.category1Id = categoryIds.value[0];
      ebook.value.category2Id = categoryIds.value[1];
      //发起修改-编辑请求
      axios.post("/ebook/save", ebook.value).then((resp) => {
        const data = resp.data;
        //判断操作是否成功
        if (data.success) {
          //成功
          //关闭对话框
          modalVisible.value = false;
          //重新查询数据
          handleQuery({
            page: pagination.value.current,
            size: pagination.value.pageSize,
          });
          //提示
          message.success("操作成功！！！");
        } else {
          //失败
          message.error(data.message);
        }
      });
    };

    //点击删除按钮触发的函数
    const handleDelete = (id: number) => {
      //发起删除请求
      axios.get("/ebook/remove", { params: { id: id } }).then((resp) => {
        const data = resp.data;
        //判断操作是否成功
        if (data.success) {
          //成功
          //重新查询数据
          handleQuery({
            page: pagination.value.current,
            size: pagination.value.pageSize,
          });
          //提示
          message.success("删除操作成功！！！");
        } else {
          //失败
          message.error("删除操作失败，请稍后再尝试！！！");
        }
      });
    };

    //点击编辑触发的函数
    const edit = (record: any) => {
      //ebook
      ebook.value = record;
      //显示对话框
      modalVisible.value = true;
      //给电子书的分类信息赋值
      categoryIds.value = [ebook.value.category1Id, ebook.value.category2Id];
    };

    //点击新增触发的函数
    const add = () => {
      //ebook清空
      ebook.value = {};
      //显示对话框
      modalVisible.value = true;
    };

    /*
     * 数据查询
     * */
    const handleQuery = (params: any) => {
      loading.value = true;
      //发起异步请求
      axios
        .get("/ebook/query", {
          params: {
            page: params.page,
            size: params.size,
            name: param.value.name,
          },
        })
        .then((resp) => {
          if (!resp.data.success) {
            message.error(resp.data.message);
          } else {
            loading.value = false;
            const data = resp.data;
            ebooks.value = data.content.list;
            //重置分页按钮、total总记录
            pagination.value.current = params.page;
            pagination.value.total = data.content.total;
          }
        });
    };
    /*
     * 表格点击页码时触发
     * */
    const handleTableChange = (pagination: any) => {
      console.log("看看自带分页的参数都有些啥：" + pagination);
      //调用分页查询操作、入参分页的页码和限制记录条数
      handleQuery({
        page: pagination.current,
        size: pagination.pageSize,
      });
    };

    //挂载完成触发的生命周期
    onMounted(() => {
      //把所有的分类信息查询出来
      handleQueryCategory();
    });

    //data返回
    return {
      ebooks,
      pagination,
      columns,
      loading,
      handleTableChange,
      modalVisible,
      modalLoading,
      handleModalOk,
      edit,
      ebook,
      add,
      handleDelete,

      imgNum,
      previewVisible,
      previewImage,
      fileList,
      handleCancel,
      previewTitle,
      customRequest,

      param,
      handleQuery,

      categoryIds,
      level1,

      getCategoryName,
    };
  },
});
</script>

<style scoped>
/* tile uploaded pictures */
.upload-list-inline :deep(.ant-upload-list-item) {
  float: left;
  width: 200px;
  margin-right: 8px;
}
.upload-list-inline [class*="-upload-list-rtl"] :deep(.ant-upload-list-item) {
  float: right;
}
</style>